import React from 'react';
import {
  Form,
  Input,
  Button,
  message,
  Modal,
  Upload,
  Space,
  Tabs,
  Select,
  InputNumber,
} from 'antd';
import { ExclamationCircleOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import UploadUtil from '@/components/UploadUtil';

const currControl = 'Edu_QuestionDtl';
const { confirm } = Modal;
const { TabPane } = Tabs;
// const playerCrt = function (vodid: string) {
//     return "//1301299150.vod2.myqcloud.com/vod-player/1301299150/" + vodid + "/tcplayer/console/vod-player.html?autoplay=false&width=1280&height=720";
// }
class QuestionDtlEdit extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      datas: {},
      imageUrl: '',
      fileList: [],
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    const { ParentData, QId } = this.props;
    if (ParentData && ParentData.id) {
      this.getData(ParentData.id);
    } else {
      var model = {
        questionBankId: QId,
      };
      this.formRef.current.setFieldsValue({ model });
    }
  }
  getData = (id: number) => {
    const { dispatch } = this.props;
    if (id) {
      dispatch({
        type: 'Abp/get',
        payload: { id },
        control: currControl,
      }).then(() => {
        var result = this.props.response.result;
        // if (result.imageUrl) {
        //     this.setState({ imageUrl: result.imageUrl });
        // }
        if (result.imageUrl) {
          var fileList: any = [];
          var pics = result.imageUrl.split(',');
          pics.forEach((element: any) => {
            var obj = {
              uid: element,
              name: element,
              response: {
                result: element,
              },
              status: 'done',
              url: UploadUtil.imgServ + element,
            };
            fileList.push(obj);
          });
          this.setState({ fileList });
        }
        this.setState({ datas: result });
        this.formRef.current.setFieldsValue({ model: result });
      });
    }
  };
  onFinish = async (values: any) => {
    var act = 'Abp/create';
    if (values.model.id) {
      act = 'Abp/update';
    }
    // if (this.state.imageUrl) {
    //     values.model.imageUrl = this.state.imageUrl;
    // }
    if (this.state.fileList) {
      var pics: string[] = [];
      this.state.fileList.forEach((element: any) => {
        pics.push(element.response.result);
      });
      values.model.imageUrl = pics.toString();
    } else {
      values.model.imageUrl = this.state.datas.imageUrl;
    }
    this.props
      .dispatch({
        type: act,
        payload: values.model,
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('保存成功！');
          this.props.fetchDatas(this.props.QId);
        } else {
          message.error('保存错误，请联系管理员');
        }
      });
  };
  ResetForm = () => {
    var data = {
      id: 0,
    };
    this.setState({ datas: data });
    this.formRef.current.resetFields();
  };
  handleDel = () => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { Id: this.state.datas.id },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('删除成功！');
          this.props.fetchDatas(this.props.ParentData.questionBankId);
          this.formRef.current.resetFields();
        } else {
          message.error('删除错误，请联系管理员！');
        }
      });
  };
  showConfirm = () => {
    var _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.handleDel();
      },
      onCancel() {},
    });
  };
  handleChange = (editorState: any) => {
    this.setState({
      contentEditor: editorState.toHTML(),
    });
  };
  onChange = (value: number[]) => {
    this.setState({
      inputValue: value,
    });
  };
  handleUpload = (info: any) => {
    if (info.file.status === 'done' && info.file.response) {
      this.setState({
        imageUrl: info.file.response.result,
      });
    }
  };
  handleUploadList = (info: any) => {
    this.setState({ fileList: info.fileList });
  };
  render() {
    const { datas, loading, fileList } = this.state;
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    return (
      <div>
        <Form ref={this.formRef} layout="vertical" onFinish={this.onFinish}>
          <Tabs defaultActiveKey="1">
            <TabPane tab="题目编辑" key="1">
              <Form.Item hidden label="id" name={['model', 'id']}>
                <Input />
              </Form.Item>
              <Form.Item hidden label="id" name={['model', 'questionBankId']}>
                <Input />
              </Form.Item>
              <Form.Item name={['model', 'title']} label="题目标题" rules={[{ required: true }]}>
                <Input />
              </Form.Item>
              <Form.Item style={{ marginBottom: 0 }}>
                <Input.Group compact>
                  <Form.Item
                    name={['model', 'questionNum']}
                    label="题目编号"
                    rules={[{ required: true }]}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                    name={['model', 'orderId']}
                    label="排序号"
                    rules={[{ required: true }]}
                  >
                    <InputNumber />
                  </Form.Item>
                  <Form.Item
                    name={['model', 'qType']}
                    label="题目类型"
                    rules={[{ required: true }]}
                  >
                    <Select style={{ width: 150 }}>
                      <Select.Option value="单选题">单选题</Select.Option>
                      <Select.Option value="多选题">多选题</Select.Option>
                    </Select>
                  </Form.Item>
                </Input.Group>
              </Form.Item>

              <Form.Item name={['model', 'contents']} label="题目内容">
                <Input.TextArea rows={4} />
              </Form.Item>
            </TabPane>
            <TabPane tab="图片" key="2">
              <Form.Item>
                <Upload
                  action={UploadUtil.actionURL}
                  headers={{
                    Authorization: UploadUtil.accessToken,
                  }}
                  data={{
                    objectId: datas.id,
                    objectName: currControl,
                    objectField: 'imageUrl',
                  }}
                  name="files"
                  listType="picture-card"
                  fileList={fileList}
                  multiple={true}
                  onChange={this.handleUploadList}
                >
                  {fileList.length >= 12 ? null : uploadButton}
                </Upload>
              </Form.Item>
            </TabPane>
            <TabPane tab="多媒体" key="3">
              <Form.Item name={['model', 'videoUrl']} label="视频地址">
                <Input />
              </Form.Item>
              <Form.Item>
                <iframe
                  src={datas.videoUrl}
                  frameBorder="0"
                  scrolling="no"
                  width="640"
                  height="368"
                  allowFullScreen
                ></iframe>
              </Form.Item>
            </TabPane>
          </Tabs>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                确定
              </Button>
              <Button onClick={this.ResetForm}>重设</Button>
              <Button danger onClick={this.showConfirm} disabled={!datas.id}>
                删除
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    );
  }
}
export default connect(({ Abp, Category }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  Category,
}))(QuestionDtlEdit);
